package com.boot.exception;
import com.boot.api.ApiResult;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice("com.boot")
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BindException.class)
    public ApiResult<String> handleException(BindException e){
        String errors = e.getBindingResult().getFieldErrors()
                .stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));//.collect(Collectors.joining("，"));
        return ApiResult.failed(errors);
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public ApiResult<String> handleIllegalArgumentException(IllegalArgumentException e){
        return ApiResult.failed(e.getMessage());
    }

    @ExceptionHandler(value = UnAuthenticationException.class)
    public ApiResult<String> handleApiException(){
        return ApiResult.unAuthentication();
    }

    @ExceptionHandler(value = ApiException.class)
    public ApiResult<String> handleApiException(ApiException e){
        return ApiResult.failed(e.getMessage());
    }

}
